package io.renren.membermanage.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.StrUtil;
import io.renren.constant.BizSystemException;
import io.renren.constant.RedisKeyConstant;
import io.renren.enums.ResultCodeEnum;
import io.renren.membermanage.service.LoginService;
import io.renren.util.RedisUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public void createCaptcha(HttpServletResponse response, String uuid) throws Exception{
        LineCaptcha lineCaptcha = null;
        try(ServletOutputStream outputStream = response.getOutputStream()) {
            lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
            //将验证码存入redis 有效时长1分钟
            String code = lineCaptcha.getCode();
            setRedisCache(RedisKeyConstant.getCaptchaKeyForC(uuid), code);
            // 输出图片流
            response.setContentType("image/gif");
            response.setHeader("Pragma", "No-cache");
            lineCaptcha.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean checkCaptcha(String uuid, String code) {
        String captcha = (String) redisUtil.get(RedisKeyConstant.getCaptchaKeyForC(uuid));
        if (StrUtil.isBlank(captcha)) {
            throw new BizSystemException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED.getCode(), ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED.getMessage());
        }
        if (!captcha.equalsIgnoreCase(code)){
            throw new BizSystemException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR.getCode(), ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR.getMessage());
        }
        if(redisUtil.exist(RedisKeyConstant.getCaptchaKeyForC(uuid))){
            redisUtil.delete(RedisKeyConstant.getCaptchaKeyForC(uuid));
        }
        return true;
    }

    private void setRedisCache(String key, String value) {
        redisUtil.set(key, value, 60L);
    }
}
